/**
 * AssistantList - Assistant List Component
 * 
 * Features:
 * - Display all assistants (builtin + custom)
 * - Filter by category (all, favorites, recent)
 * - Search assistants
 * - Select assistant
 * - Toggle favorite
 */

import { useState, useMemo } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Search, Star, Clock, Bot } from 'lucide-react';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { AssistantCard, type Assistant } from './AssistantCard';
import { useAssistantStore } from '@/store/assistant';

interface AssistantListProps {
  selectedId?: string | null;
  onSelect?: (assistant: Assistant | null) => void;
  onToggleFavorite?: (id: string) => void;
  compact?: boolean;
}

export function AssistantList({
  selectedId,
  onSelect,
  onToggleFavorite,
  compact = false,
}: AssistantListProps) {
  const { assistants, loading } = useAssistantStore();
  const [filter, setFilter] = useState<'all' | 'favorites' | 'recent'>('all');
  const [searchQuery, setSearchQuery] = useState('');

  const filteredAssistants = useMemo(() => {
    let result = assistants;

    // Apply filter
    switch (filter) {
      case 'favorites':
        result = result.filter(a => a.isFavorite);
        break;
      case 'recent':
        result = result.filter(a => a.lastUsed !== undefined);
        result.sort((a, b) => (b.lastUsed || 0) - (a.lastUsed || 0));
        break;
      default:
        // Sort by category and name
        result = [...result].sort((a, b) => {
          if (a.category !== b.category) {
            return (a.category || '').localeCompare(b.category || '');
          }
          return a.name.localeCompare(b.name);
        });
    }

    // Apply search
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(a =>
        a.name.toLowerCase().includes(query) ||
        a.description.toLowerCase().includes(query) ||
        (a.category && a.category.toLowerCase().includes(query))
      );
    }

    return result;
  }, [assistants, filter, searchQuery]);

  return (
    <div className="flex flex-col h-full">
      {/* Search */}
      {!compact && (
        <div className="p-2">
          <div className="relative">
            <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="搜索助手..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8 h-9"
            />
          </div>
        </div>
      )}

      {/* Filter Tabs */}
      {!compact && (
        <div className="flex gap-1 px-2 pb-2">
          <Button
            variant={filter === 'all' ? 'secondary' : 'ghost'}
            size="sm"
            className="flex-1 h-8"
            onClick={() => setFilter('all')}
          >
            <Bot className="w-3 h-3 mr-1" />
            全部
          </Button>
          <Button
            variant={filter === 'favorites' ? 'secondary' : 'ghost'}
            size="sm"
            className="flex-1 h-8"
            onClick={() => setFilter('favorites')}
          >
            <Star className="w-3 h-3 mr-1" />
            收藏
          </Button>
          <Button
            variant={filter === 'recent' ? 'secondary' : 'ghost'}
            size="sm"
            className="flex-1 h-8"
            onClick={() => setFilter('recent')}
          >
            <Clock className="w-3 h-3 mr-1" />
            最近
          </Button>
        </div>
      )}

      {/* Assistant List */}
      <ScrollArea className="flex-1">
        <div className={compact ? 'p-1 space-y-0.5' : 'p-2 space-y-1'}>
          {/* Default Assistant */}
          <AssistantCard
            assistant={{
              id: 'default',
              name: '通用助手',
              description: '默认的 AI 助手，可以帮助您完成各种任务',
              category: undefined,
              isBuiltin: true,
            }}
            selected={selectedId === null || selectedId === 'default'}
            onClick={() => onSelect?.(null)}
            compact={compact}
          />

          {/* Loading State */}
          {loading && (
            <div className="py-8">
              <LoadingSpinner size="md" />
            </div>
          )}

          {/* Empty State */}
          {!loading && filteredAssistants.length === 0 && (
            <div className="text-center py-4 text-sm text-muted-foreground">
              {searchQuery ? '未找到匹配的助手' : '暂无助手'}
            </div>
          )}

          {/* Assistants */}
          {!loading && filteredAssistants.map((assistant) => (
            <AssistantCard
              key={assistant.id}
              assistant={assistant}
              selected={selectedId === assistant.id}
              onClick={() => onSelect?.(assistant)}
              onToggleFavorite={onToggleFavorite}
              compact={compact}
            />
          ))}
        </div>
      </ScrollArea>
    </div>
  );
}

